﻿using CCWin;
using CCWin.SkinControl;
using ERPWinFormWork.Material.Material.Dtos;
using ERPWinFormWork.Sales;
using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.TestCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ERPWinFormWork.Sales.Form1;

namespace ERPWinFormWork.Test
{
    public partial class Inspection : Form
    {
        private ApiClient _apiClient;
        // 为出/入货分别维护分页参数
        private int OutPageIndex { get; set; } = 1;
        private int OutPageSize { get; set; } = 15;
        private int OutTotalCount { get; set; }
        private int OutTotalPages { get; set; }

        private int InPageIndex { get; set; } = 1;
        private int InPageSize { get; set; } = 15;
        private int InTotalCount { get; set; }
        private int InTotalPages { get; set; }

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalCount { get; set; }
        private int TotalPages { get; set; }


        public Inspection()
        {
            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);

            // 配置表格，添加操作列
            ConfigureDataGridViews();

            // （可选）重置后如果需要清空表格数据，重新加载默认无筛选数据

            Loaddetetype();
            Loadtool();
            LoadDropdownData();
            LoadProduct();
            LoadMaterial();
            LoadSuppilrt();

            GetData();

            GetInData();

            GetInspectionData();

            GetPurData();


        }


        /// <summary>
        /// 配置数据表格，添加操作列
        /// </summary>
        private void ConfigureDataGridViews()
        {
            // 配置出货检验表格
            ConfigureDataGridView(dgvoutproduct);

            // 配置入货检验表格
            ConfigureDataGridView(dgvInmater);

            // 配置采购核价表格
            ConfigureDataGridView(dgvprocur);
        }

        /// <summary>
        /// 配置单个数据表格
        /// </summary>
        /// <param name="grid">要配置的DataGridView</param>
        private void ConfigureDataGridView(DataGridView grid)
        {
            if (grid == null) return;

            // 设置表格属性
            grid.AllowUserToAddRows = false;
            grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grid.MultiSelect = true;

            // 绑定事件
            grid.CellContentClick += DataGridView_CellContentClick;
            grid.CellClick += DataGridView_CellClick;
            grid.DataBindingComplete += DataGridView_DataBindingComplete;
        }



        /// <summary>
        /// 表格单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var grid = sender as DataGridView;
            if (grid == null) return;

            var columnName = grid.Columns[e.ColumnIndex].Name;

            // 采购核价页：额外支持“详情”，并使用采购专用删除逻辑
            if (grid == dgvprocur)
            {
                if (!(grid.Rows[e.RowIndex].DataBoundItem is GetProcurement_PricingDtos pro)) return;
                if (columnName == "colDetail")
                {
                    var form = new ProcurementPricingDetail(pro.Id);
                    form.Show();
                    return;
                }
                if (columnName == "colEdit")
                {
                    // 检查审核状态，已审核的记录不允许编辑
                    if (!string.IsNullOrWhiteSpace(pro.State) && pro.State == "已审核")
                    {
                        MessageBox.Show("该记录已审核，无法进行编辑操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    try
                    {
                        // 传递刷新回调函数，编辑成功后自动刷新采购核价列表
                        var form = new UpdateProcurement_Pricing(pro.Id, () =>
                        {
                            // 编辑成功后刷新采购核价列表数据
                            GetPurData();
                        });
                        form.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"打开编辑窗体失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
                if (columnName == "colDelete")
                {
                    // 检查审核状态，已审核的记录不允许删除
                    if (!string.IsNullOrWhiteSpace(pro.State) && pro.State == "已审核")
                    {
                        MessageBox.Show("该记录已审核，无法进行删除操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    DeleteProcurementById(pro.Id, pro.PricingNode);
                    return;
                }
            }

            // 其他页面：沿用通用编辑/删除逻辑
            if (columnName == "colEdit")
            {
                // 编辑功能
                EditInspectionRecord(grid, e.RowIndex);
            }
            else if (columnName == "colDelete")
            {
                // 单个删除功能
                DeleteInspectionRecord(grid, e.RowIndex);
            }
        }

        /// <summary>
        /// 表格数据绑定完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var grid = sender as DataGridView;
            if (grid == null) return;

            // 确保操作列存在
            EnsureOperationColumns(grid);

            // 更新按钮文本
            UpdateDeleteButtonText(grid);

            // 采购核价页面：根据审核状态控制操作按钮
            if (grid == dgvprocur)
            {
                UpdateProcurementOperationButtons();
            }
        }

        /// <summary>
        /// 表格单元格点击事件（处理表头复选框）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            var grid = sender as DataGridView;
            if (grid == null || e.RowIndex < 0) return;

            // 如果点击的是复选框列
            if (e.ColumnIndex >= 0 && grid.Columns[e.ColumnIndex].Name == "colCheckBox")
            {
                // 切换复选框状态
                bool currentValue = grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null &&
                                   (bool)grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = !currentValue;

                // 更新按钮文本
                UpdateDeleteButtonText(grid);
            }
        }

        /// <summary>
        /// 表头点击事件（处理全选/取消全选）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var grid = sender as DataGridView;
            if (grid == null || e.ColumnIndex < 0) return;

            // 如果点击的是复选框列的表头
            if (grid.Columns[e.ColumnIndex].Name == "colCheckBox")
            {
                // 检查当前是否全选
                bool allChecked = true;
                foreach (DataGridViewRow row in grid.Rows)
                {
                    if (row.Cells["colCheckBox"].Value == null || !(bool)row.Cells["colCheckBox"].Value)
                    {
                        allChecked = false;
                        break;
                    }
                }

                // 切换全选状态
                foreach (DataGridViewRow row in grid.Rows)
                {
                    row.Cells["colCheckBox"].Value = !allChecked;
                }

                // 更新按钮文本
                UpdateDeleteButtonText(grid);
            }
        }

        /// <summary>
        /// 确保操作列存在
        /// </summary>
        /// <param name="grid">DataGridView</param>
        private void EnsureOperationColumns(DataGridView grid)
        {
            // 添加复选框列
            if (!grid.Columns.Contains("colCheckBox"))
            {
                var checkBoxCol = new DataGridViewCheckBoxColumn
                {
                    Name = "colCheckBox",
                    HeaderText = "选择",
                    Width = 50,
                    ReadOnly = false
                };
                grid.Columns.Add(checkBoxCol);
            }

            // 采购核价页额外增加“详情”列，其余页面不加
            bool isProcurement = (grid == dgvprocur);
            if (isProcurement && !grid.Columns.Contains("colDetail"))
            {
                var detailCol = new DataGridViewButtonColumn
                {
                    Name = "colDetail",
                    HeaderText = "详情",
                    Text = "详情",
                    UseColumnTextForButtonValue = true,
                    Width = 60
                };
                grid.Columns.Add(detailCol);
            }

            // 添加编辑列
            if (!grid.Columns.Contains("colEdit"))
            {
                var editCol = new DataGridViewButtonColumn
                {
                    Name = "colEdit",
                    HeaderText = "编辑",
                    Text = "编辑",
                    UseColumnTextForButtonValue = true,
                    Width = 60
                };
                grid.Columns.Add(editCol);
            }

            // 添加删除列
            if (!grid.Columns.Contains("colDelete"))
            {
                var deleteCol = new DataGridViewButtonColumn
                {
                    Name = "colDelete",
                    HeaderText = "删除",
                    Text = "删除",
                    UseColumnTextForButtonValue = true,
                    Width = 60
                };
                grid.Columns.Add(deleteCol);
            }

            // 将复选框列放到最前面，操作列放到最后；采购核价有“详情”列
            int count = grid.Columns.Count;
            if (count > 0)
            {
                grid.Columns["colCheckBox"].DisplayIndex = 0;  // 复选框列放在第一列
                if (isProcurement && grid.Columns.Contains("colDetail"))
                {
                    grid.Columns["colDetail"].DisplayIndex = count - 3;
                    grid.Columns["colEdit"].DisplayIndex = count - 2;
                    grid.Columns["colDelete"].DisplayIndex = count - 1;
                }
                else
                {
                    grid.Columns["colEdit"].DisplayIndex = count - 2;
                    grid.Columns["colDelete"].DisplayIndex = count - 1;
                }
            }

            // 绑定表头点击事件
            grid.ColumnHeaderMouseClick += DataGridView_ColumnHeaderMouseClick;
        }

        /// <summary>
        /// 编辑检验记录
        /// </summary>
        /// <param name="grid">DataGridView</param>
        /// <param name="rowIndex">行索引</param>
        private void EditInspectionRecord(DataGridView grid, int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= grid.Rows.Count) return;

            var row = grid.Rows[rowIndex];

            // 根据表格类型判断使用哪个DTO
            if (grid == dgvoutproduct && row.DataBoundItem is OutInspectionListDtos outInspection)
            {
                try
                {
                    // 打开出货检验编辑窗体，传递检验ID和刷新回调
                    var updateForm = new UpdateOutInspection(outInspection.Id, () =>
                    {
                        // 编辑成功后刷新出货检验列表数据
                        GetData();
                    });
                    updateForm.Show();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"打开编辑窗体时出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (grid == dgvInmater && row.DataBoundItem is InInspectionListDtos inInspection)
            {
                try
                {
                    // 打开入货检验编辑窗体，传递检验ID和刷新回调
                    var updateForm = new UpdateInInspection(inInspection.Id, () =>
                    {
                        // 编辑成功后刷新入货检验列表数据
                        GetInData();
                    });
                    updateForm.Show();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"打开编辑窗体时出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 删除单个检验记录（按检验编号）
        /// </summary>
        /// <param name="grid">DataGridView</param>
        /// <param name="rowIndex">行索引</param>
        private async void DeleteInspectionRecord(DataGridView grid, int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= grid.Rows.Count) return;

            var row = grid.Rows[rowIndex];
            string node = string.Empty;

            // 根据表格类型判断使用哪个DTO
            if (grid == dgvoutproduct && row.DataBoundItem is OutInspectionListDtos outInspection)
            {
                node = outInspection.InspectionNode ?? string.Empty;
            }
            else if (grid == dgvInmater && row.DataBoundItem is InInspectionListDtos inInspection)
            {
                node = inInspection.InspectionNode ?? string.Empty;
            }

            if (string.IsNullOrWhiteSpace(node))
            {
                MessageBox.Show("该记录缺少检验编号，无法删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var result = MessageBox.Show($"确定要删除检验编号：{node} 的记录？", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                await DeleteInspectionRecordsByNodes(new List<string> { node });
            }
        }

        /// <summary>
        /// 批量删除检验记录（按检验编号）
        /// </summary>
        /// <param name="grid">DataGridView</param>
        private async void BatchDeleteInspectionRecords(DataGridView grid)
        {
            if (grid == null)
            {
                MessageBox.Show("表格控件为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var nodes = new List<string>();
            var recordNames = new List<string>();

            // 遍历所有行，检查复选框是否被选中
            foreach (DataGridViewRow row in grid.Rows)
            {
                if (row.Cells["colCheckBox"].Value != null && (bool)row.Cells["colCheckBox"].Value)
                {
                    string node = string.Empty;

                    // 根据表格类型判断使用哪个DTO
                    if (grid == dgvoutproduct && row.DataBoundItem is OutInspectionListDtos outInspection)
                    {
                        node = outInspection.InspectionNode ?? string.Empty;
                    }
                    else if (grid == dgvInmater && row.DataBoundItem is InInspectionListDtos inInspection)
                    {
                        node = inInspection.InspectionNode ?? string.Empty;
                    }

                    if (!string.IsNullOrWhiteSpace(node))
                    {
                        nodes.Add(node);
                        recordNames.Add(node);
                    }
                }
            }

            if (nodes.Count == 0)
            {
                MessageBox.Show("请先勾选要删除的记录（需要有效的检验编号）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 显示要删除的记录详情
            string recordDetails = string.Join("\n", recordNames.Take(5)); // 只显示前5条
            if (recordNames.Count > 5)
            {
                recordDetails += $"\n... 还有 {recordNames.Count - 5} 条记录";
            }

            var result = MessageBox.Show(
                $"确定要删除选中的 {nodes.Count} 条检验记录吗？\n\n检验编号：\n{recordDetails}",
                "确认批量删除",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                await DeleteInspectionRecordsByNodes(nodes);
            }
        }

        /// <summary>
        /// 按检验编号删除检验记录（调用API）
        /// </summary>
        /// <param name="inspectionNodes">要删除的检验编号列表</param>
        private async Task DeleteInspectionRecordsByNodes(List<string> inspectionNodes)
        {
            try
            {
                if (inspectionNodes == null || inspectionNodes.Count == 0)
                {
                    MessageBox.Show("没有要删除的检验编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var validNodes = inspectionNodes.Where(n => !string.IsNullOrWhiteSpace(n)).ToList();
                if (validNodes.Count == 0)
                {
                    MessageBox.Show("没有有效的检验编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 以数组 query 方式传递：/api/Write/DelGoods_Inspection?inspectionnodes=a&inspectionnodes=b
                string qs = string.Join("&", validNodes.Select(n => $"inspectionnodes={Uri.EscapeDataString(n)}"));
                string endpointWithQuery = "api/Write/DelGoods_Inspection" + (string.IsNullOrEmpty(qs) ? string.Empty : ("?" + qs));

                Console.WriteLine($"删除请求(按编号)URL：{endpointWithQuery}");

                var response = await _apiClient.DeleteAsync<TestApiResult<string>>(
                    endpoint: endpointWithQuery,
                    parameters: null
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show($"成功删除 {validNodes.Count} 条检验记录", "删除成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 清除复选框选择
                    ClearAllCheckBoxes(dgvoutproduct);
                    ClearAllCheckBoxes(dgvInmater);

                    // 刷新数据
                    RefreshDataAfterDelete();
                }
                else
                {
                    MessageBox.Show($"删除失败：{response?.msg ?? "未知错误"}", "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除过程中出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"删除异常详情：{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 根据Id删除采购核价记录
        /// </summary>
        private async void DeleteProcurementById(int id, string node)
        {
            if (id <= 0) return;
            var confirm = MessageBox.Show($"确定删除核价：{node}？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (confirm != DialogResult.Yes) return;
            try
            {
                var resp = await _apiClient.DeleteAsync<TestApiResult<string>>($"api/Write/DelProcurement_Pricing?id={id}");
                if (resp != null && resp.code == 200)
                {
                    MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    GetPurData();
                }
                else
                {
                    MessageBox.Show($"删除失败：{resp?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除后刷新数据
        /// </summary>
        private void RefreshDataAfterDelete()
        {
            try
            {
                // 删除后保持当前页有效
                if (OutPageIndex > OutTotalPages && OutTotalPages > 0) OutPageIndex = OutTotalPages;
                if (InPageIndex > InTotalPages && InTotalPages > 0) InPageIndex = InTotalPages;

                // 刷新出货检验数据
                GetData();

                // 刷新入货检验数据
                GetInData();

                Console.WriteLine("数据刷新完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"刷新数据时出现异常：{ex.Message}");
            }
        }

        /// <summary>
        /// 清除所有复选框选择
        /// </summary>
        /// <param name="grid">DataGridView</param>
        private void ClearAllCheckBoxes(DataGridView grid)
        {
            if (grid == null) return;

            foreach (DataGridViewRow row in grid.Rows)
            {
                if (row.Cells["colCheckBox"] != null)
                {
                    row.Cells["colCheckBox"].Value = false;
                }
            }
        }

        /// <summary>
        /// 出货检验显示
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
            {
                    { "pageindex", OutPageIndex.ToString() },
                    { "pagesize", OutPageSize.ToString() },
                    { "inspection_Type","2"},
                    { "inspectionNodeOrName", this.textinspectionNodeOrName.Text },
                    { "shipment_Date", this.datetimeshipment_Date.Text },
                    { "inspection_Date", this.datetimeinspection_Date.Text },
                    { "batch", this.textbatch.Text },
                    { "detection_Result", this.cbodetection_Result.Text }

            };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }

            var response = await _apiClient.GetAsync<TestApiResult<List<OutInspectionListDtos>>>(
                    endpoint: "api/Read/GetGoods_Inspection",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                dgvoutproduct.DataSource = response.pageDatas;
                // 更新分页信息
                textoutpageindex.Text=OutPageIndex.ToString();
                OutTotalCount = response.totalCount;
                OutTotalPages = response.totalPage;
                // 更新分页显示（如果有对应的标签控件）
                UpdateOutPaginationDisplay();
            }
        }

        /// <summary>
        /// 出货检验查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchoutproduct_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();
            // 部门ID（从下拉框选的值）
            if (cbodepartment_Id.SelectedValue != null)
            {
                queryParams["department_Id"] = ((int)cbodepartment_Id.SelectedValue).ToString();
            }


            //产品ID（从下拉框选的值）
            if (cboproductId.SelectedValue != null)
            {
                queryParams["productId"] = ((int)cboproductId.SelectedValue).ToString();
            }

            OutPageIndex = 1;
            GetData(queryParams);
        }


        /// <summary>
        /// 入货检验显示
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetInData(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
            {
                    { "pageindex", InPageIndex.ToString() },
                    { "pagesize", InPageSize.ToString() },
                    { "inspection_Type","1"},
                    { "inspectionNodeOrName", this.textIninspectionNodeOrName.Text },
                    { "shipment_Date", this.dateInshipment_Date.Text },
                    { "inspection_Date", this.dateIninspection_Date.Text},
                    { "batch", this.textInbatch.Text },
                    { "detection_Result", this.cboIndetection_Result.Text }

            };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }

            var Inresponse = await _apiClient.GetAsync<TestApiResult<List<InInspectionListDtos>>>(
                    endpoint: "api/Read/GetGoods_Inspection",
                    parameters: parameters // 传递查询参数
                );
            // 处理响应结果
            if (Inresponse != null && Inresponse.code == 200)
            {
                dgvInmater.DataSource = Inresponse.pageDatas;
                // 更新分页信息
                textinpageindex.Text=InPageIndex.ToString();
                InTotalCount = Inresponse.totalCount;
                InTotalPages = Inresponse.totalPage;
                // 更新分页显示（如果有对应的标签控件）
                UpdateInPaginationDisplay();
            }
        }



        // 加载部门下拉框数据
        private async Task LoadDropdownData()
        {
            // 示例：加载部门下拉框
            var deptResponse = await _apiClient.GetAsync<TestApiResult<List<DepartmentDtos>>>(
                endpoint: "api/Read/GetDepartment");

            if (deptResponse != null && deptResponse.code == 200)
            {
                // 清空并添加默认项
                cbodepartment_Id.Items.Clear();
                cbodepartment_Id.DisplayMember = "departmentName"; // 显示部门名称
                cbodepartment_Id.ValueMember = "id";                 // 实际值存部门 ID
                cboIndepartment_Id.Items.Clear();
                cboIndepartment_Id.DisplayMember = "departmentName"; // 显示部门名称
                cboIndepartment_Id.ValueMember = "id";                 // 实际值存部门 ID


                cbodepartment_Id.DataSource = deptResponse.data;
                cboIndepartment_Id.DataSource = deptResponse.data;
                cbodepartment_Id.SelectedItem = null;
                cboIndepartment_Id.SelectedItem = null;
            }

        }

        // 加载产品下拉框数据
        private async Task LoadProduct()
        {
            // 示例：加载产品下拉框
            var productResponse = await _apiClient.GetAsync<TestApiResult<List<ProductDtos>>>(
                endpoint: "api/Read/GetProduct");

            if (productResponse != null && productResponse.code == 200)
            {
                // 清空并添加默认项
                cboproductId.Items.Clear();
                cboproductId.DisplayMember = "product_Name"; // 显示名称
                cboproductId.ValueMember = "id";                 // 实际值存 ID
                cboproductId.DataSource = productResponse.data;
                cboproductId.SelectedItem = null;
            }
        }

        // 加载物料下拉框数据
        private async Task LoadMaterial()
        {
            // 示例：加载物料下拉框
            var materialResponse = await _apiClient.GetAsync<TestApiResult<List<Material_TableDtos>>>(
                endpoint: "api/Read/GetMaterial_Table");

            if (materialResponse != null && materialResponse.code == 200)
            {
                // 清空并添加默认项
                cboInmaterialId.Items.Clear();
                cboInmaterialId.DisplayMember = "materialName"; // 显示名称
                cboInmaterialId.ValueMember = "id";                 // 实际值存 ID
                cboInmaterialId.DataSource = materialResponse.data;
                cboInmaterialId.SelectedItem = null;
            }
        }


        /// <summary>
        /// 出货检验重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnqclick_Click(object sender, EventArgs e)
        {
            textinspectionNodeOrName.Text = string.Empty;
            textbatch.SkinTxt.Text = string.Empty;

            cboproductId.Text = string.Empty;
            cbodepartment_Id.Text = string.Empty;
            cbodetection_Result.Text = string.Empty;
            datetimeshipment_Date.text = string.Empty;
            datetimeinspection_Date.text = string.Empty;
            OutPageIndex = 1;
            GetData();
        }

        /// <summary>
        /// 出货检验新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnaddoutproduct_Click(object sender, EventArgs e)
        {
            AddOutInspection addOutInspection = new AddOutInspection(() =>
            {
                // 添加成功后刷新出货检验列表数据
                GetData();
            });
            addOutInspection.Show();
        }
        /// <summary>
        /// 入货检验重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQ_Click(object sender, EventArgs e)
        {
            textIninspectionNodeOrName.Text = string.Empty;
            textInbatch.Text = string.Empty;

            cboInmaterialId.Text = string.Empty;

            cboIndepartment_Id.Text = string.Empty;
            cboIndetection_Result.Text = string.Empty;
            dateInshipment_Date.text = string.Empty;
            dateIninspection_Date.text = string.Empty;

            InPageIndex = 1;
            GetInData();
        }

        /// <summary>
        /// 入货检验查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInserch_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();
            // 部门ID（从下拉框选的值）
            if (cboIndepartment_Id.SelectedValue != null)
            {
                queryParams["department_Id"] = ((int)cboIndepartment_Id.SelectedValue).ToString();
            }


            //物料ID（从下拉框选的值）
            if (cboInmaterialId.SelectedValue != null)
            {
                queryParams["materialId"] = ((int)cboInmaterialId.SelectedValue).ToString();
            }

            InPageIndex = 1;
            GetInData(queryParams);
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInmater_Click(object sender, EventArgs e)
        {
            AddInInspection addInInspection = new AddInInspection(() =>
            {
                // 添加成功后刷新入货检验列表数据
                GetInData();
            });
            addInInspection.Show();
        }

        /// <summary>
        /// 出货检验批量删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btndelallproduct_Click(object sender, EventArgs e)
        {
            if (dgvoutproduct.Rows.Count == 0)
            {
                MessageBox.Show("当前没有出货检验数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int selectedCount = GetSelectedCount(dgvoutproduct);
            if (selectedCount > 0)
            {
                btndelallproduct.Text = $"删除({selectedCount})";
            }
            else
            {
                btndelallproduct.Text = "删除";
            }

            BatchDeleteInspectionRecords(dgvoutproduct);
        }

        /// <summary>
        /// 入货检验批量删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnclosemater_Click(object sender, EventArgs e)
        {
            if (dgvInmater.Rows.Count == 0)
            {
                MessageBox.Show("当前没有入货检验数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int selectedCount = GetSelectedCount(dgvInmater);
            if (selectedCount > 0)
            {
                btnclosemater.Text = $"删除({selectedCount})";
            }
            else
            {
                btnclosemater.Text = "删除";
            }

            BatchDeleteInspectionRecords(dgvInmater);
        }

        /// <summary>
        /// 获取选中的记录数量
        /// </summary>
        /// <param name="grid">DataGridView</param>
        /// <returns>选中的记录数量</returns>
        private int GetSelectedCount(DataGridView grid)
        {
            if (grid == null) return 0;

            int count = 0;
            foreach (DataGridViewRow row in grid.Rows)
            {
                if (row.Cells["colCheckBox"].Value != null && (bool)row.Cells["colCheckBox"].Value)
                {
                    count++;
                }
            }
            return count;
        }

        /// <summary>
        /// 更新删除按钮文本
        /// </summary>
        /// <param name="grid">DataGridView</param>
        private void UpdateDeleteButtonText(DataGridView grid)
        {
            if (grid == null) return;

            int selectedCount = GetSelectedCount(grid);

            if (grid == dgvoutproduct)
            {
                if (selectedCount > 0)
                {
                    btndelallproduct.Text = $"删除({selectedCount})";
                }
                else
                {
                    btndelallproduct.Text = "删除";
                }
            }
            else if (grid == dgvInmater)
            {
                if (selectedCount > 0)
                {
                    btnclosemater.Text = $"删除({selectedCount})";
                }
                else
                {
                    btnclosemater.Text = "删除";
                }
            }
        }

        /// <summary>
        /// 更新采购核价页面的操作按钮状态（根据审核状态）
        /// </summary>
        private void UpdateProcurementOperationButtons()
        {
            if (dgvprocur == null || dgvprocur.Rows.Count == 0) return;

            foreach (DataGridViewRow row in dgvprocur.Rows)
            {
                if (row.DataBoundItem is GetProcurement_PricingDtos procurement)
                {
                    bool isReviewed = !string.IsNullOrWhiteSpace(procurement.State) && procurement.State == "已审核";

                    // 根据审核状态设置按钮的可用性和文本
                    if (dgvprocur.Columns.Contains("colEdit"))
                    {
                        var editButton = row.Cells["colEdit"] as DataGridViewButtonCell;
                        if (editButton != null)
                        {
                            if (isReviewed)
                            {
                                editButton.Value = "已审核";
                                editButton.Style.BackColor = Color.LightGray;
                                editButton.Style.ForeColor = Color.Gray;
                            }
                            else
                            {
                                editButton.Value = "编辑";
                                editButton.Style.BackColor = Color.White;
                                editButton.Style.ForeColor = Color.Black;
                            }
                        }
                    }

                    if (dgvprocur.Columns.Contains("colDelete"))
                    {
                        var deleteButton = row.Cells["colDelete"] as DataGridViewButtonCell;
                        if (deleteButton != null)
                        {
                            if (isReviewed)
                            {
                                deleteButton.Value = "已审核";
                                deleteButton.Style.BackColor = Color.LightGray;
                                deleteButton.Style.ForeColor = Color.Gray;
                            }
                            else
                            {
                                deleteButton.Value = "删除";
                                deleteButton.Style.BackColor = Color.White;
                                deleteButton.Style.ForeColor = Color.Black;
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        ///  出货检验上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOutPrev_Click(object sender, EventArgs e)
        {
            if (OutPageIndex > 1)
            {
                OutPageIndex--;
                GetData();
            }
        }

        /// <summary>
        /// 出货检验下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOutNext_Click(object sender, EventArgs e)
        {
            if (OutPageIndex < OutTotalPages)
            {
                OutPageIndex++;
                GetData();
            }
        }

        /// <summary>
        /// 来料检验的下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInNext_Click(object sender, EventArgs e)
        {

            if (InPageIndex < InTotalPages)
            {
                InPageIndex++;
                GetInData();
            }
        }

        /// <summary>
        /// 来料检验的上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInPrev_Click(object sender, EventArgs e)
        {
            if (InPageIndex > 1)
            {
                InPageIndex--;
                GetInData();
            }
        }


        ///// <summary>
        ///// 更新出货检验分页显示
        ///// </summary>
        private void UpdateOutPaginationDisplay()
        {
            lblOutPageInfo.Text = $"第 {OutPageIndex} 页，共 {OutTotalPages} 页，总计 {OutTotalCount}条记录";
        }



        ///// <summary>
        ///// 更新入货检验分页显示
        ///// </summary>
        private void UpdateInPaginationDisplay()
        {
            lblInPageInfo.Text = $"第 {InPageIndex} 页，共 {InTotalPages} 页，总计 {InTotalCount} 条记录";
        }


        /// <summary>
        /// 获取检测项目
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetInspectionData(Dictionary<string, string> customParams = null)
        {
            var detec = new Dictionary<string, string>
            {
                    { "pageindex", OutPageIndex.ToString() },
                    { "pagesize", OutPageSize.ToString() },
                    { "inspection_Type","2"},
                    { "items_Name", this.textitems_Name.Text }

            };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    detec[kv.Key] = kv.Value;
                }
            }

            var response = await _apiClient.GetAsync<TestApiResult<List<Testing_ItemsDtos>>>(
                    endpoint: "api/Read/GetTesting_Items",
                    parameters: detec // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                dgvdete.DataSource = response.data;
            }
        }
        /// <summary>
        /// 检测项查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton2_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();
            if (cbodetection_TypeId.SelectedValue != null)
            {
                queryParams["detection_TypeId"] = ((int)cbodetection_TypeId.SelectedValue).ToString();
            }

            if (cbotesting_ToolsId.SelectedValue != null)
            {
                queryParams["testing_ToolsId"] = ((int)cbotesting_ToolsId.SelectedValue).ToString();
            }
            GetInspectionData(queryParams);
        }
        /// <summary>
        /// 检测项重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton1_Click(object sender, EventArgs e)
        {
            textitems_Name.Text = string.Empty;
            cbodetection_TypeId.Text = string.Empty;
            cbotesting_ToolsId.Text = string.Empty;
            GetInspectionData();
        }

        // 加载检测类型下拉框数据
        private async Task Loaddetetype()
        {
            var deteResponse = await _apiClient.GetAsync<TestApiResult<List<Detection_TypeDtos>>>(
                endpoint: "api/Read/GetDetection_Type");

            if (deteResponse != null && deteResponse.code == 200)
            {
                // 清空并添加默认项
                cbodetection_TypeId.Items.Clear();
                cbodetection_TypeId.DisplayMember = "detectionType_Name"; // 显示名称
                cbodetection_TypeId.ValueMember = "id";                 // 实际值存 ID
                cbodetection_TypeId.DataSource = deteResponse.data;
                cbodetection_TypeId.SelectedItem = null;
            }
        }

        // 加载检测工具下拉框数据
        private async Task Loadtool()
        {
            var toolResponse = await _apiClient.GetAsync<TestApiResult<List<Testing_ToolsDtos>>>(
                endpoint: "api/Read/GetTesting_Tools");

            if (toolResponse != null && toolResponse.code == 200)
            {
                // 清空并添加默认项
                cbotesting_ToolsId.Items.Clear();
                cbotesting_ToolsId.DisplayMember = "tools_Name"; // 显示名称
                cbotesting_ToolsId.ValueMember = "id";                 // 实际值存 ID
                cbotesting_ToolsId.DataSource = toolResponse.data;
                cbotesting_ToolsId.SelectedItem = null;
            }
        }

        /// <summary>
        /// 新增检测项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton5_Click(object sender, EventArgs e)
        {
            var addForm = new AddTesting_Items(() =>
            {
                // 添加成功后刷新检测项列表数据
                GetInspectionData();
            });
            addForm.Show();
        }





        // 加载供应商下拉框数据
        private async Task LoadSuppilrt()
        {
            // 示例：加载物料下拉框
            var suppilerResponse = await _apiClient.GetAsync<TestApiResult<List<Supplier_TableDtos>>>(
                endpoint: "api/Read/GetSupplier_Table");

            if (suppilerResponse != null && suppilerResponse.code == 200)
            {
                // 清空并添加默认项
                cbosupplierId.Items.Clear();
                cbosupplierId.DisplayMember = "supplierName"; // 显示名称
                cbosupplierId.ValueMember = "id";                 // 实际值存 ID
                cbosupplierId.DataSource = suppilerResponse.data;
                cbosupplierId.SelectedItem = null;
            }
        }




        /// <summary>
        /// 获取采购核价
        /// </summary>
        /// <param name="customParams"></param>
        private async void GetPurData(Dictionary<string, string> customParams = null)
        {
            var purse = new Dictionary<string, string>
            {
                    { "pageindex", PageIndex.ToString() },
                    { "pagesize", PageSize.ToString() },
                    { "pricingNodeOrName", this.textpricingNodeOrName.Text },
                    { "pricing_Date", this.datepricing_Date.Text },

            };

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    purse[kv.Key] = kv.Value;
                }
            }

            var response = await _apiClient.GetAsync<TestApiResult<List<GetProcurement_PricingDtos>>>(
                    endpoint: "api/Read/GetProcurement_Pricing",
                    parameters: purse // 传递查询参数
                );
            // 处理响应结果
            if (response != null && response.code == 200)
            {
                dgvprocur.DataSource = response.pageDatas;
                // 更新分页信息
                textpropageindex.Text = PageIndex.ToString();
                TotalCount = response.totalCount;
                TotalPages = response.totalPage;
                // 更新分页显示（如果有对应的标签控件）
                UpdateProcurementDisplay();
            }
        }


        /// <summary>
        /// 采购核价重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnresetQuotation_Click(object sender, EventArgs e)
        {
            textpricingNodeOrName.Text = string.Empty;
            datepricing_Date.Text = string.Empty;
            cbosupplierId.Text = string.Empty;
            PageIndex = 1;
            GetPurData();
        }
        /// <summary>
        /// 采购核价查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuotationGet_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();
            if (cbosupplierId.SelectedValue != null)
            {
                queryParams["supplierId"] = ((int)cbosupplierId.SelectedValue).ToString();
            }
            PageIndex = 1;
            GetPurData(queryParams);
        }
        /// <summary>
        /// 采购核价新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuotationAdd1_Click(object sender, EventArgs e)
        {
            using (var addProcurement_Pricing = new AddProcurement_Pricing())
            {
                var result = addProcurement_Pricing.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    GetPurData();
                }
            }

        }
        /// <summary>
        /// 采购核价导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinButton3_Click(object sender, EventArgs e)
        {
            try
            {
                var purse = new Dictionary<string, string>
                {
                    { "pageindex", PageIndex.ToString() },
                    { "pagesize", PageSize.ToString() },
                    { "pricingNodeOrName", this.textpricingNodeOrName.Text },
                    { "pricing_Date", this.datepricing_Date.Text },
                };

                // 供应商筛选
                if (cbosupplierId != null && cbosupplierId.SelectedValue != null)
                {
                    purse["supplierId"] = ((int)cbosupplierId.SelectedValue).ToString();
                }


                byte[] excelBytes = await _apiClient.GetBytesAsync(
                    endpoint: "api/Read/Procurement_PricingExport",
                    parameters: purse);

                if (excelBytes == null || excelBytes.Length == 0)
                {
                    MessageBox.Show("导出失败：返回内容为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                using (var saveDialog = new SaveFileDialog())
                {
                    saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*";
                    saveDialog.Title = "保存采购核价导出文件";
                    saveDialog.FileName = $"采购核价_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    saveDialog.RestoreDirectory = true;

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);
                            var openChoice = MessageBox.Show(
                                $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                                "导出成功",
                                MessageBoxButtons.YesNo,
                                MessageBoxIcon.Information);
                            if (openChoice == DialogResult.Yes)
                            {
                                System.Diagnostics.Process.Start(saveDialog.FileName);
                            }
                        }
                        catch (UnauthorizedAccessException)
                        {
                            MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        catch (System.IO.IOException ex)
                        {
                            MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出过程中出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        /// <summary>
        /// 采购核价审核（批量）：根据勾选的记录收集核价编号并批量修改状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinButton6_Click(object sender, EventArgs e)
        {
            if (dgvprocur == null || dgvprocur.Rows.Count == 0)
            {
                MessageBox.Show("当前没有可审核的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedNodes = new List<string>();
            foreach (DataGridViewRow row in dgvprocur.Rows)
            {
                bool isChecked = false;
                if (row.Cells["colCheckBox"] != null && row.Cells["colCheckBox"].Value != null)
                {
                    bool.TryParse(row.Cells["colCheckBox"].Value.ToString(), out isChecked);
                }
                if (!isChecked) continue;

                if (row.DataBoundItem is GetProcurement_PricingDtos item)
                {
                    // 已审核跳过
                    if (!string.IsNullOrWhiteSpace(item.State) && item.State == "已审核") continue;
                    if (!string.IsNullOrWhiteSpace(item.PricingNode)) selectedNodes.Add(item.PricingNode);
                }
            }

            if (selectedNodes.Count == 0)
            {
                MessageBox.Show("请先勾选需要审核的记录（未审核且有核价编号）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var confirm = MessageBox.Show($"确认审核选中的 {selectedNodes.Count} 条记录？", "审核确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (confirm != DialogResult.Yes) return;

            try
            {
                // 以数组 query 方式传递：/api/Write/ReviewProcurement_Pricing?procurement_PricingNode=a&procurement_PricingNode=b
                string qs = string.Join("&", selectedNodes.Select(n => $"procurement_PricingNode={Uri.EscapeDataString(n)}"));
                string endpoint = "api/Write/ReviewProcurement_Pricing" + (string.IsNullOrEmpty(qs) ? string.Empty : ("?" + qs));

                // 发送非空请求体，避免部分服务端对空体PUT拦截
                var response = await _apiClient.PutAsync<string, TestApiResult<string>>(endpoint, "{}");
                if (response != null && response.code == 200)
                {
                    var msg = string.IsNullOrWhiteSpace(response.msg) ? "审核成功" : response.msg;
                    MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearAllProcurementCheckBoxes();
                    GetPurData();
                }
                else
                {
                    MessageBox.Show($"审核失败：{response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"审核过程中出现异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清除采购核价选中复选框
        /// </summary>
        private void ClearAllProcurementCheckBoxes()
        {
            if (dgvprocur == null) return;
            foreach (DataGridViewRow row in dgvprocur.Rows)
            {
                if (row.Cells["colCheckBox"] != null) row.Cells["colCheckBox"].Value = false;
            }
        }


        /// <summary>
        /// 采购核价下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnpronext_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalPages)
            {
                PageIndex++;
                GetPurData();
            }
        }
        /// <summary>
        /// 采购核价上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnproprev_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                GetPurData();
            }
        }

        ///// <summary>
        ///// 更新采购核价分页显示
        ///// </summary>
        private void UpdateProcurementDisplay()
        {
            lblprocurement.Text = $"第 {PageIndex} 页，共 {TotalPages} 页，总计 {TotalCount} 条记录";
        }
        /// <summary>
        /// 采购核价跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnprogopage_Click(object sender, EventArgs e)
        {
            // 验证输入的页码
            if (int.TryParse(textpropageindex.Text.Trim(), out int targetPage))
            {
                // 检查页码是否有效
                if (targetPage < 1 || targetPage > TotalPages)
                {
                    MessageBox.Show($"请输入有效的页码（1-{TotalPages}）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    textpropageindex.Focus();
                    return;
                }

                // 如果页码没有变化，无需刷新
                if (targetPage == PageIndex)
                    return;

                // 更新页码并加载数据
                PageIndex = targetPage;
                GetPurData();
            }
            else
            {
                // 输入不是有效的数字
                MessageBox.Show("请输入有效的页码数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textpropageindex.Focus();
            }
        }
        /// <summary>
        /// 来料检验跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btningopage_Click(object sender, EventArgs e)
        {
            // 验证输入的页码
            if (int.TryParse(textinpageindex.Text.Trim(), out int intargetPage))
            {
                // 检查页码是否有效
                if (intargetPage < 1 || intargetPage > InTotalPages)
                {
                    MessageBox.Show($"请输入有效的页码（1-{InTotalPages}）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    textinpageindex.Focus();
                    return;
                }

                // 如果页码没有变化，无需刷新
                if (intargetPage == InPageIndex)
                    return;

                // 更新页码并加载数据
                InPageIndex = intargetPage;
                GetInData();
            }
            else
            {
                // 输入不是有效的数字
                MessageBox.Show("请输入有效的页码数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textinpageindex.Focus();
            }
        }
        /// <summary>
        /// 出货检验跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnoutpage_Click(object sender, EventArgs e)
        {
            // 验证输入的页码
            if (int.TryParse(textoutpageindex.Text.Trim(), out int outtargetPage))
            {
                // 检查页码是否有效
                if (outtargetPage < 1 || outtargetPage > OutTotalPages)
                {
                    MessageBox.Show($"请输入有效的页码（1-{OutTotalPages}）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    textoutpageindex.Focus();
                    return;
                }

                // 如果页码没有变化，无需刷新
                if (outtargetPage == OutPageIndex)
                    return;

                // 更新页码并加载数据
                OutPageIndex = outtargetPage;
                GetData();
            }
            else
            {
                // 输入不是有效的数字
                MessageBox.Show("请输入有效的页码数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textinpageindex.Focus();
            }
        }
    }
}
